import { defineStore } from 'pinia'
import { register, unregister } from '@tauri-apps/plugin-global-shortcut'
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'

interface Settings {
  maxItems: number
  startWithSystem: boolean
  minimizeToTray: boolean
  shortcut: string
}

const SETTINGS_KEY = 'clip-manager-settings'

export const useSettingsStore = defineStore('settings', {
  state: () => ({
    maxItems: 50,
    startWithSystem: false,
    minimizeToTray: true,
    shortcut: 'CommandOrControl+Space'
  } as Settings),

  actions: {
    async loadSettings() {
      try {
        const settingsStr = localStorage.getItem(SETTINGS_KEY)
        if (settingsStr) {
          const settings = JSON.parse(settingsStr)
          this.$patch(settings)
        }
        // 注册快捷键
        await this.registerShortcut()
      } catch (error) {
        console.error('Failed to load settings:', error)
      }
    },

    async updateSettings(settings: Settings) {
      try {
        // 如果快捷键发生变化，需要重新注册
        if (settings.shortcut !== this.shortcut) {
          await this.unregisterShortcut()
          this.$patch(settings)
          await this.registerShortcut()
        } else {
          this.$patch(settings)
        }
        localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings))
      } catch (error) {
        console.error('Failed to save settings:', error)
      }
    },

    async registerShortcut() {
      try {
        await register(this.shortcut, async () => {
          // 显示窗口并聚焦
          const windows = WebviewWindow.getCurrent()
          await windows.show()
          await windows.unminimize()
          await windows.setFocus()

        })
      } catch (error) {
        console.error('Failed to register shortcut:', error)
      }
    },

    async unregisterShortcut() {
      try {
        await unregister(this.shortcut)
      } catch (error) {
        console.error('Failed to unregister shortcut:', error)
      }
    }
  }
}) 